package com.watson.activity;

import static com.watson.fragment.HomeFragment.U_DEPOT_ID;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.watson.BaseActivity;
import com.watson.LoginActivity;
import com.watson.MyApp;
import com.watson.R;
import com.watson.adapter.CodeAdapter;
import com.watson.adapter.DetailsAdapter;
import com.watson.http.CommonHttpConsts;
import com.watson.http.HttpCallbackData;
import com.watson.http.HttpClient;
import com.watson.utils.DialogUitl;
import com.watson.utils.LogUtils;
import com.watson.utils.SPUtils;
import com.watson.utils.StringUtils;
import com.watson.utils.ToastUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class DetailsActivity extends BaseActivity {
    private TextView tvTitle, tvbillsort, tvTime, tvout_storage, tvStatus;
    private AppCompatButton btnKu, btnBack, btnClaim, btnWithdraw, btnCancellation;
    private RelativeLayout lyInside;
    private String no, zt;
    private RecyclerView recyclerData;
    private DetailsAdapter detailsAdapter;
    private ArrayList<Map> dataList;
    private int isType = 0;
    private NestedScrollView sNestedScrollView;
    private Map dataMap;
    private ArrayList<Map> codelist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        statusbar4();
        dataMap = new HashMap();
        dataList = new ArrayList<>();
        codelist = new ArrayList<>();
        no = getIntent().getStringExtra("no");
        zt = getIntent().getStringExtra("zt");
        isType = getIntent().getIntExtra("type", 0);
        initView();
        initClick();
        get_WMS_sendsList(no, zt);
    }

    private void initClick() {
        findViewById(R.id.imgBack).setOnClickListener(v -> finish());
        findViewById(R.id.tvSideslip).setOnClickListener(v -> {
            dismiss();
            if (codelist.size() > 0) {
                detailsPop();
            } else {
                ToastUtil.show("暂无扫码记录");
            }
        });
        btnClaim.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            if (dataList.size() > 0) {
                add_WMS_OutboundTask(dataList.get(0).get("no") + "", StringUtils.getDeviceSN(mContext));
            }
        });

        btnWithdraw.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog(1);
        });

        btnCancellation.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) {
                return;
            }
            exitDialog(0);
        });
    }

    public void exitDialog(int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.dialog);
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_exit, null);
        TextView tvDelete = v.findViewById(R.id.tvDelete);
        TextView tvName = v.findViewById(R.id.tvName);
        TextView tvSave = v.findViewById(R.id.tvSave);
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
        if (type == 1) {
            tvName.setText("确认撤销订单吗");
        }
        if (type == 0) {
            tvName.setText("确认作废订单吗");
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);
        tvDelete.setOnClickListener(v1 -> dialog.dismiss());

        tvSave.setOnClickListener(view -> {
            delete_WMS_OutboundTask(type);
            dialog.dismiss();
        });
    }

    private void initView() {
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText("详情");
        lyInside = findViewById(R.id.lyInside);
        tvStatus = findViewById(R.id.tvStatus);
        recyclerData = findViewById(R.id.recyclerData);
        recyclerData.setLayoutManager(new LinearLayoutManager(mContext));
        detailsAdapter = new DetailsAdapter(mContext, dataList);
        recyclerData.setAdapter(detailsAdapter);
        tvbillsort = findViewById(R.id.tvbillsort);
        tvout_storage = findViewById(R.id.tvout_storage);
        tvTime = findViewById(R.id.tvTime);
        btnKu = findViewById(R.id.btnKu);
        btnBack = findViewById(R.id.btnBack);
        btnClaim = findViewById(R.id.btnClaim);
        btnWithdraw = findViewById(R.id.btnWithdraw);
        btnCancellation = findViewById(R.id.btnCancellation);
        sNestedScrollView = findViewById(R.id.sNestedScrollView);
        sNestedScrollView.post(() -> sNestedScrollView.fullScroll(ScrollView.FOCUS_UP));
    }

    private void setView(Map map) {
        tvbillsort.setText(map.get("billsource") + "");
        tvout_storage.setText((StringUtils.isEmpty(map.get("out_storage") + "") ? "" : map.get("out_storage") + "")
                + "-->" + (StringUtils.isEmpty(map.get("in_storage") + "") ? "" : map.get("in_storage") + ""));
        tvTime.setText(map.get("lastbillsort") + "-" + map.get("lastbillno"));
        String status = map.get("status") + "";//单据状态
        if (StringUtils.isEmpty(status)) {
            status = "";
        }
        //出库单详情  打包中 状态显示 领单, 打包完成 状态显示 显示撤单 作废，返回打包
        if (isType == 1) {
            String isreceive = map.get("isreceive") + "";
            if (isreceive.equals("0")) {
                btnClaim.setVisibility(View.VISIBLE);
            }
//            if (status.equals("打包中")) {
//                btnClaim.setVisibility(View.VISIBLE);
//            } else
            if (status.equals("打包完成")) {
                btnBack.setVisibility(View.VISIBLE);
                btnWithdraw.setVisibility(View.VISIBLE);
                btnCancellation.setVisibility(View.VISIBLE);
            }
        } else if (isType == 2) {
            if (status.equals("打包中")) {
                btnKu.setVisibility(View.VISIBLE);
                btnWithdraw.setVisibility(View.VISIBLE);
                btnCancellation.setVisibility(View.VISIBLE);
            } else if (status.equals("打包完成")) {
                btnKu.setVisibility(View.VISIBLE);
                btnBack.setVisibility(View.VISIBLE);
                btnWithdraw.setVisibility(View.VISIBLE);
                btnCancellation.setVisibility(View.VISIBLE);
            }
        }

        // 待打印  打包中  打包完成  待出库  待收货  已发货  已收货
        if (status.equals("待打印")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status1));
        } else if (status.equals("打包中")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status2));
        } else if (status.equals("打包完成")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status2));
        } else if (status.equals("待出库")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status3));
        } else if (status.equals("已发货")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status4));
        } else if (status.equals("待收货")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.status5));
        } else if (status.equals("已收货")) {
            tvStatus.setText(status);
            tvStatus.setTextColor(mContext.getResources().getColor(R.color.tv333));
        } else {
            tvStatus.setText(status);
        }

        String R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        if (!R_Auth_Code.contains("WMS_ClAIMTICKET")) {
            btnClaim.setVisibility(View.GONE);
        } else if (!R_Auth_Code.contains("WMS_TASK_QRCK")) {
            btnKu.setVisibility(View.GONE);
        } else if (!R_Auth_Code.contains("WMS_TASK_CD")) {
            btnWithdraw.setVisibility(View.GONE);
        } else if (!R_Auth_Code.contains("WMS_TASK_ZF")) {
            btnCancellation.setVisibility(View.GONE);
        } else if (!R_Auth_Code.contains("WMS_TASK_FH")) {
            btnBack.setVisibility(View.GONE);
        }
        // WMS_ClAIMTICKET  领单
        // WMS_TASK_QRCK  出库
        // WMS_TASK_FH   返回打包
        // WMS_TASK_CD 撤单
        // WMS_TASK_ZF 作废
    }

    private void get_WMS_sendsList(String id, String zt) {
        HttpClient.getInstance().getData(CommonHttpConsts.get_WMS_sendsList, "get_WMS_sendsList")//
                .headers("token", SPUtils.get(mContext, "token", "") + "").params("no", id)//单号
                .params("zt", zt)//单据归属
                .params("type", isType)//接口类型 1出库单列表2任务列表3出库记录列表
                .execute(new HttpCallbackData() {
                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        if (code == 1001 && !StringUtils.isEmpty(info)) {
                            ArrayList<Map> data = new ArrayList<>();
                            data = (ArrayList<Map>) JSON.parseArray(info, Map.class);
                            if (data.size() > 0) {
                                if (data.get(0).containsKey("codelists")) {
                                    codelist = (ArrayList<Map>) JSON.parseArray(data.get(0).get("codelists") + "", Map.class);
                                    detailsAdapter.setCode(codelist.size());
                                }
                                dataMap = data.get(0);
                                dataList = (ArrayList<Map>) JSON.parseArray(data.get(0).get("details") + "", Map.class);
                                detailsAdapter.setData(dataList);

                                setView(dataMap);
                            }
                        } else {
                            ToastUtil.show(msg);
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void add_WMS_OutboundTask(String no, String sn) {
        String R_Auth_Code = SPUtils.get(mContext, "auth", "") + "";
        Map data = new HashMap();
        data.put("no", no);
        data.put("sn", sn);
        data.put("taskrecipient", SPUtils.get(mContext, "U_Name", "") + "");
        data.put("taskrecipientid", SPUtils.get(mContext, "U_Id", "") + "");//任务领取人id
        data.put("wh", U_DEPOT_ID + "");//作业仓库
        if (R_Auth_Code.contains("WMS_SCAN_ClAIMTICKET")) {
            data.put("authcode", "WMS_SCAN_ClAIMTICKET");
        } else {
            data.put("authcode", "");
        }
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.add_WMS_OutboundTask, "add_WMS_OutboundTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.show(msg);
                        if (code == 1001) {
                            Intent data = new Intent();
                            data.putExtra("name", true);
                            setResult(RESULT_OK, data);
                            finish();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void delete_WMS_OutboundTask(int type) {
        Map data = new HashMap();
        data.put("no", dataMap.get("no"));
        data.put("type", type);//0作废，1撤单
        String datStr = new Gson().toJson(data);
        HttpClient.getInstance().postData(CommonHttpConsts.delete_WMS_OutboundTask, "delete_WMS_OutboundTask")
                .headers("token", SPUtils.get(mContext, "token", "") + "")
                .upJson(datStr)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.show(msg);
                        if (code == 1001) {
                            Intent data = new Intent();
                            data.putExtra("name", true);
                            setResult(RESULT_OK, data);
                            finish();
                        }
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void dismiss() {
        if (detailsPop != null) {
            detailsPop.dismiss();
        }
    }

    private PopupWindow detailsPop;

    private void detailsPop() {
        View v = View.inflate(mContext, R.layout.layout_popup_details, null);
        RecyclerView recyclerCode = v.findViewById(R.id.recyclerCode);
        TextView tvNum = v.findViewById(R.id.tvNum);
        recyclerCode.setLayoutManager(new LinearLayoutManager(mContext));
        CodeAdapter codeAdapter = new CodeAdapter(mContext, codelist);
//        CodeAdapter codeAdapter = new CodeAdapter(mContext, codesupplierList);
        recyclerCode.setAdapter(codeAdapter);
        if (dataList.size() > 0) {
            codeAdapter.setDataList(dataList);
        }
        detailsPop = new PopupWindow(v, 500, ViewGroup.LayoutParams.MATCH_PARENT);
        // 点击框外可以使得popupwindow消失
        detailsPop.setFocusable(true);
        detailsPop.setOutsideTouchable(false);
        detailsPop.setTouchable(true);
        detailsPop.setBackgroundDrawable(new BitmapDrawable());
        detailsPop.showAtLocation(lyInside, Gravity.RIGHT, 0, -120);
        tvNum.setText("（" + codelist.size() + "）");
    }
}
